package cn.fayang.basic.service.impl;

import cn.fayang.basic.constants.BaseConstant;
import cn.fayang.basic.dto.LoginDto;
import cn.fayang.basic.dto.WeChatdDto;
import cn.fayang.basic.exception.BusinessException;
import cn.fayang.basic.service.ILoginService;
import cn.fayang.basic.util.AjaxResult;
import cn.fayang.basic.util.HttpClientUtils;
import cn.fayang.basic.util.MD5Utils;
import cn.fayang.basic.util.StrUtils;
import cn.fayang.user.domain.Logininfo;
import cn.fayang.user.domain.User;
import cn.fayang.user.domain.Wxuser;
import cn.fayang.user.mapper.LogininfoMapper;
import cn.fayang.user.mapper.UserMapper;
import cn.fayang.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Map<String, Object> account(LoginDto dto) {
        String password = dto.getPassword();
        String username = dto.getUsername();
        Integer type = dto.getType();
        //非空判断
        if(StringUtils.isEmpty(password) || StringUtils.isEmpty(username) ||StringUtils.isEmpty(type) ){
            new BusinessException("用户名密码不能为空!!!");
        }
        //数据库查询登录信息
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username,type);
        //如果为空则用户不存在
        if(logininfo == null){
            new BusinessException("用户不存在!!!");
        }
        //获取盐值
        String salt = logininfo.getSalt();
        String md5Tmp = MD5Utils.encrypByMd5(password + salt);
        System.out.println(md5Tmp);
        System.out.println(logininfo.getPassword());
        if(!md5Tmp.equals(logininfo.getPassword())){
            new BusinessException("账号或密码错误");
        }

        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;
    }

    @Override
    public AjaxResult wechat(WeChatdDto dto) {
        String code = dto.getCode();
        if(StringUtils.isEmpty(code)){
            new BusinessException("code不能为空");
        }
        //从微信获取token
        String tokenURl = BaseConstant.WeChatConstants.TOKEN_URL.replace("APPID", BaseConstant.WeChatConstants.APPID)
                .replace("SECRET", BaseConstant.WeChatConstants.SECRET)
                .replace("CODE", code);
        //接收微信返回的token字符串
        String tokenStr = HttpClientUtils.httpGet(tokenURl);
        //将JSON的字符串转化为对象
        JSONObject wxToken = JSONObject.parseObject(tokenStr);
        //从JSON对象中获取access_token
        String accessToken = wxToken.getString("access_token");
        //从JSON对象中获取openid
        String openId = wxToken.getString("openid");
        //通过openid查询wxuser
        Wxuser wxuser = wxuserMapper.loadByOpenid(openId);
        //如果wxuser和userID不为空说明以前注册过直接登录
        if(wxuser != null && wxuser.getUserId() != null){
            Logininfo logininfo = logininfoMapper.loadByUserID(wxuser.getUserId());
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);
            return AjaxResult.me().setResultObj(map);
        }
        String binderParams = "?accessToken="+accessToken+"&openId="+openId;
        return AjaxResult.me().setSuccess(false).setResultObj(binderParams);

    }

    @Override
    public Map<String, Object> binder(WeChatdDto dto) {
        User user = userMapper.loadByPhone(dto.getPhone());
        Logininfo logininfo = null;
        if(user != null){
            logininfo = logininfoMapper.loadByUserID(user.getId());
        }else {
            user = dto2User(dto);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        String wxUserUrl = BaseConstant.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN",dto.getAccessToken())
                .replace("OPENID",dto.getOpenId());
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
//        3.根据微信的用户基本信息生成t_wxuser
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
//        4.t_wxuser绑定t_user
        wxuser.setUserId(user.getId());
//        5.保存t_wxuser（完成了整个绑定流程）
        wxuserMapper.save(wxuser);
//        6.直接免密登录
        //4.1 存储redis
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,//对象要序列化
                30,
                TimeUnit.MINUTES
        );
        //4.2 返回token + logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //密码等敏感信息不返回前端
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//注意：一定要手动设置type 前端用户注册  1
        return logininfo;
    }

    private User dto2User(WeChatdDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }
}
